class MessageController {

  def authenticateService
  
  def index = { redirect(action: all, params: params) }

  // the delete, save and update actions only accept POST requests
  static allowedMethods = [delete: 'POST', save: 'POST', update: 'POST']

  def all = {
    if (!params.max) params.max = 10
    [messageInstanceList: Message.list(params)]
  }

  def user = {
    def user = User.get(params.id)
    if (!user) {
      flash.message = "User ${params.id} not found "
      redirect(action: all)
    } else {
      render(view: 'all', model: [messageInstanceList: Message.findAllByUser(user, params), filter: user.username])
    }
  }

  def show = {
    def messageInstance = Message.get(params.id)

    if (!messageInstance) {
      flash.message = "Message not found with id ${params.id}"
      redirect(action: all)
    }
    else { return [messageInstance: messageInstance] }
  }

  def delete = {
    def messageInstance = Message.get(params.id)
    if (messageInstance && (messageInstance.user == authenticateService.userDomain() || authenticateService.ifAllGranted(Role.ADMIN))) {
      messageInstance.delete()
      flash.message = "Message ${params.id} deleted"
      redirect(action: all)
    }
    else {
      flash.message = "Message not found with id ${params.id} or no permission to delete message"
      redirect(action: all)
    }
  }

  def edit = {
    def messageInstance = Message.get(params.id)
    if (!messageInstance || (messageInstance.user != authenticateService.userDomain() && !authenticateService.ifAllGranted(Role.ADMIN))) {
      flash.message = "Message not found with id ${params.id} or no permission to change message"
      redirect(action: all)
    }
    else {
      return [messageInstance: messageInstance]
    }
  }

  def update = {
    def messageInstance = Message.get(params.id)
    if (messageInstance && (messageInstance.user == authenticateService.userDomain() || authenticateService.ifAllGranted(Role.ADMIN))) {
      if (params.version) {
        def version = params.version.toLong()
        if (messageInstance.version > version) {

          messageInstance.errors.rejectValue("version", "message.optimistic.locking.failure", "Another user has updated this Message while you were editing.")
          render(view: 'edit', model: [messageInstance: messageInstance])
          return
        }
      }
      messageInstance.properties = params
      if (!messageInstance.hasErrors() && messageInstance.save()) {
        flash.message = "Message ${params.id} updated"
        redirect(action: show, id: messageInstance.id)
      }
      else {
        render(view: 'edit', model: [messageInstance: messageInstance])
      }
    }
    else {
      flash.message = "Message not found with id ${params.id} or no permission to change message"
      redirect(action: edit, id: params.id)
    }
  }

  def create = {
    def messageInstance = new Message()
    messageInstance.properties = params
    return ['messageInstance': messageInstance]
  }

  def save = {
    def messageInstance = new Message(params)
    if (messageInstance.content.size() > 255) messageInstance.content = messageInstance.content.substring(0, 254)
    if (!messageInstance.hasErrors() && messageInstance.save()) {
      flash.message = "Thanks ${messageInstance.user} for submitting your message "
      redirect(action: all)
    }
    else {
      render(view: 'all', model: [messageInstance: messageInstance])
    }
  }

  def feed = {
    if (!params.max) params.max = 15
    def results = Message.list(params)
    render(contentType: "text/xml") {
      rss(version:'2.0') {
        channel {
          title ("MoTSangria Activity Log")
          link ("http://${request.serverName}:${request.serverPort}${request.contextPath}/message/all")
          description("MoTSangria activity log showing the last ${params.max} messages submitted to the MoTSangria homepage")
          for (m in results) {
            item {
              title("${m.user}: ${m.content}")
              description("${m.user}: ${m.content} (via: ${m.medium} ${DateTagLib.getNiceDate(m.dateCreated)})")
              link ("http://${request.serverName}:${request.serverPort}${request.contextPath}/message/show/${m.id}")
              guid ("http://${request.serverName}:${request.serverPort}${request.contextPath}/message/show/${m.id}")
              pubDate("${m.dateCreated}")
            }
          }
        }
      }
    }
  }

}